<script setup lang="ts">
import { ref } from 'vue'
import { message } from 'ant-design-vue'
import { getProductByIdUsingGet, updateProductUsingPut } from '@/api/productController.ts'
import ImageUpload from '@/components/ImageUpload.vue'

interface Props {
  isOpen?: boolean
  closeModal?: () => void
  refreshData?: () => void
}

const props = withDefaults(defineProps<Props>(), {
  isOpen: false,
  closeModal: () => {},
  refreshData: () => {},
})

const product = ref<API.Product>({})

const getProductInfo = async (id: number) => {
  if (!id) {
    return
  }
  const res = await getProductByIdUsingGet({ id })
  if (res.code === 200 && res.data) {
    product.value = res.data as API.Product
  } else {
    message.error(res.message)
  }
}

// 提交
const doSubmit = async () => {
  if (!product.value.id) {
    return
  }
  const res = await updateProductUsingPut({
    ...product.value,
  })
  if (res.code === 200 && res.data) {
    message.success('修改成功')
    props.closeModal?.()
    props.refreshData?.()
  } else {
    message.error(res.message)
  }
}

// 回调函数
const onSuccess = (newImage: string) => {
  product.value.image = newImage
}

defineExpose({
  getProductInfo,
})
</script>

<template>
  <div id="product-detail-view">
    <a-modal
      v-model:open="props.isOpen"
      title="编辑商品信息"
      ok-text="提交"
      cancel-text="取消"
      @cancel="props.closeModal()"
      @ok="doSubmit"
    >
      <a-form :model="product">
        <a-form-item label="图片">
          <image-upload :product="product" :on-success="onSuccess" />
        </a-form-item>
        <a-form-item label="名称">
          <a-input v-model:value="product.name" />
        </a-form-item>
        <a-form-item label="描述">
          <a-input v-model:value="product.description" />
        </a-form-item>
        <a-form-item label="价格">
          <a-input v-model:value="product.price" />
        </a-form-item>
        <a-form-item label="库存">
          <a-input v-model:value="product.stock" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped></style>
